package com.leon.alishop.spider.util;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class SpiderStringUtil {

	/**
	 * 移出所有空格
	 * @param input
	 * @return
	 */
	public static String removeAllBlank(String input){
		int len = input.length();
		StringBuffer sb = new StringBuffer(len);
		char[] inputCharArr = input.toCharArray();
		for (char c : inputCharArr) {
			if(!Character.isWhitespace(c))
				sb.append(c);
		}
		return sb.toString();
	}
	
	/**
	 * 解析请求参数
	 * @param url
	 * @return
	 */
	public static Map<String,String[]> parseRequestUrlParams(String url){
		int indexof = url.indexOf('?');
		if(indexof<=0)
			return Collections.emptyMap();
		String queryStr = url.substring(indexof+1,url.length());
		int ampersandIndex,lastAmpersandIndex = 0,pvIndex;
		String subStr,param,value;
		Map<String,String[]> paramsMap = new HashMap<String, String[]>();
		String[] valueArrTemp;
		do{
			ampersandIndex = queryStr.indexOf('&', lastAmpersandIndex)+1;
			if(ampersandIndex>0){
				subStr = queryStr.substring(lastAmpersandIndex, ampersandIndex-1);
				lastAmpersandIndex = ampersandIndex;
			}else{
				subStr = queryStr.substring(lastAmpersandIndex);
			}
			pvIndex = subStr.indexOf("=");
			if(pvIndex == -1 || pvIndex == subStr.length()-1)
				continue;
			param = subStr.substring(0,pvIndex);
			value = subStr.substring(pvIndex+1,subStr.length());
//			param = pvIndex>=0 ? subStr.substring(0,pvIndex) : subStr;
//			value = pvIndex>=0 ? subStr.substring(pvIndex+1,subStr.length()): "";
			if(paramsMap.containsKey(param)){
				valueArrTemp = Arrays.copyOf(paramsMap.get(param), paramsMap.get(param).length+1);
				valueArrTemp[paramsMap.get(param).length] = value;
				paramsMap.put(param, valueArrTemp);
			}else{
				valueArrTemp = new String[]{value};
				paramsMap.put(param, valueArrTemp);
			}
		}while(ampersandIndex>0);
		return paramsMap;
	}
}
